# -*-coding:utf-8-*-
import base64
import pickle

from django_redis import get_redis_connection


def merge_collect_cookie_to_redis(request, user, response):
    """
    合并请求用户的收藏数据,将未登录保存在cookie里的保存到redis中
    遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    :param request: 用户请求
    :param user: 当前登录用户
    :param response: 响应
    :return:
    """
    # 获取cookie中的购物车
    cookie_collect = request.COOKIES.get('collect')
    if not cookie_collect:
        return response

    # 解析cookie购物车数据
    cookie_collect = pickle.loads(base64.b64decode(cookie_collect.encode()))

    # 用于保存向redis购物车商品数量hash添加数据的字典
    collect = {}

    # 记录redis勾选状态中应该增加的book_id
    redis_collect_selected_add = []

    # 记录redis勾选状态中应该删除的book_id
    redis_collect_selected_remove = []

    # 合并cookie购物车与redis购物车，保存到collect字典中
    for book_id, count_selected_dict in cookie_collect.items():
        # 处理商品数量
        collect[book_id] = count_selected_dict['duration']

        if count_selected_dict['selected']:
            redis_collect_selected_add.append(book_id)
        else:
            redis_collect_selected_remove.append(book_id)

    if collect:
        redis_conn = get_redis_connection('collect')
        pl = redis_conn.pipeline()
        pl.hmset('collect_%s' % user.id, collect)
        if redis_collect_selected_add:
            pl.sadd('collect_selected_%s' % user.id, *redis_collect_selected_add)
        if redis_collect_selected_remove:
            pl.srem('collect_selected_%s' % user.id, *redis_collect_selected_remove)
        pl.execute()

    response.delete_cookie('collect')

    return response